package com.wei.myhame.model.http;


import com.wei.myhame.constants.Constant;
import com.wei.myhame.model.api.LoginServiceApi;
import com.wei.myhame.model.api.MyServiceApi;
import com.wei.myhame.model.api.PlanServiceApi;
import com.wei.myhame.model.api.SportServiceApi;
import com.wei.myhame.utils.SystemUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpManager {
    private static MyServiceApi myServiceApi;       //我的页面
    private static LoginServiceApi loginServiceApi; //登录注册

    private static SportServiceApi sportServiceApi; //运动页面
    private static PlanServiceApi planServiceApi; //计划页面

    private static Cache cache;

    //创建Retrofit对象
    private static Retrofit getRetrofit(String url){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getOkhttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit;
    }

    /**
     * 创建带缓存的HttpClient对象
     * @return
     */
    private static OkHttpClient getOkhttpClient() {
        //本地缓存文件
        File file = new File(Constant.PATH_CACHE);
        /*OutputStream outputStream=null;
        FileInputStream inputStream = null;
        if(file.exists()){
            try {
                inputStream = new FileInputStream(file);
                outputStream = new ByteArrayOutputStream();
                byte[] bts = new byte[1028*8];
                int lg = 0;
                while((lg = inputStream.read(bts)) != -1){
                    outputStream.write(bts,0,lg);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(outputStream != null){
                    int size = ((ByteArrayOutputStream) outputStream).toByteArray().length;
                    float mb = size/(1024*1024); //单位MB

                }
            }
        }*/
        //设置缓存文件的大小100M
        cache = new Cache(file, 1024 * 1024 * 100);
        return new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(new Myintercepter())
                .addNetworkInterceptor(new Myintercepter())
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    /**
     * 获取当前缓存的大小
     * @return
     */
    public static String getCurrentCacheSize(){
        String mb = "";
        try {
            //计算当前缓存的大小
            if(cache.size() < 1024){
                mb = cache.size()+"kb";
            }else{
                mb = cache.size()/(1024*1024)+"MB";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mb;
    }

    /**
     * 清理网络数据缓存
     */
    public static void clearCurrentCache(){
        if(cache != null){
            try {
                cache.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取相关的网络接口
    private static synchronized <T> T getServerApis(String baseUrl,Class<T> tCla){
        return getRetrofit(baseUrl).create(tCla);
    }

    /**
     * 获取我的接口api
     * @return
     */
    public static MyServiceApi getMyServiceApi(){
        synchronized (HttpManager.class){
            if(myServiceApi == null){
                synchronized (HttpManager.class){
                    myServiceApi = getServerApis(Constant.BASE_URL,MyServiceApi.class);
                }
            }
        }
        return myServiceApi;
    }

    /**
     * 获取登录注册接口api
     * @return
     */
    public static LoginServiceApi getLoginServiceApi(){
        synchronized (HttpManager.class){
            if(loginServiceApi == null){
                synchronized (HttpManager.class){
                    loginServiceApi = getServerApis(Constant.BASE_URL,LoginServiceApi.class);
                }
            }
        }
        return loginServiceApi;
    }

    /**
     * 获取运动页面接口api
     * @return
     */
    public static SportServiceApi getSportServiceApi(){
        synchronized (HttpManager.class){
            if(sportServiceApi == null){
                synchronized (HttpManager.class){
                    sportServiceApi = getServerApis(Constant.BASE_URL,SportServiceApi.class);
                }
            }
        }
        return sportServiceApi;
    }

    /**
     * 计划页面接口api
     * @return
     */
    public static PlanServiceApi getPlanServiceApi(){
        synchronized (HttpManager.class){
            if(planServiceApi == null){
                synchronized (HttpManager.class){
                    planServiceApi = getServerApis(Constant.BASE_URL,PlanServiceApi.class);
                }
            }
        }
        return planServiceApi;
    }

    //拦截器的实现类
    private static class Myintercepter implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if(!SystemUtils.checkNetWork()){
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response response = chain.proceed(request);
            if(!SystemUtils.checkNetWork()){
                int maxAge = 0;
                return response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control","public ,max-age="+maxAge).build();
            }else{
                int maxStale = 60*60*24*28; //设置缓存数据的保存时间
                return response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control","public, onlyif-cached, max-stale="+maxStale).build();
            }
        }
    }
}
